//  @ Project : GagalPanen
//  @ File Name : sprites.cpp
//  @ Date : 3/9/2011
//  @ Author : 
//
//

#include <assert.h>
#include "sprites.hpp"
#include "watersprite.hpp"
#include "harvestsprite.hpp"
#include "sicklesprite.hpp"

Sprites::Sprites(GameInterface* game) :
  game_(game), sprites_() {
  sprites_.push_back(new WaterSprite(game_));
  sprites_.push_back(new HarvestSprite(game_));
  sprites_.push_back(new SickleSprite(game_));
}

Sprites::Sprites(GameInterface* game, std::ifstream& is) :
  game_(game), sprites_() {
  int n;
  is >> n;
  for (int i = 0; i < n; ++i) {
    std::string buffer;
    is >> buffer;
    if (buffer == "WATER") {
      sprites_.push_back(new WaterSprite(game, is));
    } else if (buffer == "HARVEST") {
      sprites_.push_back(new HarvestSprite(game, is));
    } else if (buffer == "SICKLE") {
      sprites_.push_back(new SickleSprite(game, is));
    } else {
      assert(false);
    }
  }
}

void Sprites::save(std::ofstream& os) {
  os << sprites_.size() << std::endl;
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    if (sprites_[i]->getType() == kWater) {
      os << "WATER" << std::endl;
    } else if (sprites_[i]->getType() == kHarvest) {
      os << "HARVEST" << std::endl;
    } else if (sprites_[i]->getType() == kSickle) {
      os << "SICKLE" << std::endl;
    } else if (sprites_[i]->getType() == kPlow) {
      os << "PLOW" << std::endl;
    } else {
      assert(false);
    }
    sprites_[i]->save(os);
  }
}

Sprites::~Sprites() {
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    delete sprites_[i];
  }
}

void Sprites::advanceDay() {
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    sprites_[i]->advanceDay();
  }
  return;
}

void Sprites::advanceTime() {
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    sprites_[i]->advanceTime();
  }
  return;
}

bool Sprites::containsSpriteAt(Cell* cell) {
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    if (sprites_[i]->getCell() == cell) {
      if (sprites_[i]->isSleep() == false) {
        return true;
      }
    }
  }
  return false;
}
Sprite* Sprites::getOneSpriteAt(Cell* cell) {
  assert(containsSpriteAt(cell));
  for (int i = 0; i < (int)sprites_.size(); ++i) {
    if (sprites_[i]->getCell() == cell) {
      if (sprites_[i]->isSleep() == false) {
        return sprites_[i];
      }
    }
  }
  assert(false);
}

  int Sprites::getSpritesCount() {
    return sprites_.size();
  }

  /*
   1 based indexing
   */
  Sprite* Sprites::getSpriteOfIndex(int index) {
    assert(index > 0 && index <= getSpritesCount());
    return sprites_[index-1];
  }

